package com.kaiupup.study.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.kaiupup.study.dto.TokenResult;
import jdk.nashorn.internal.parser.Token;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @projectName: kaiupup-online-taxi
 * @package: com.kaiupup.study.util
 * @className: JwtUtils
 * @author: kaiupup
 * @description: TODO
 * @date: 2024/2/4 05:24
 * @version: 1.0
 */
public class JwtUtils {

    private static final String SIGN = "CPFkaiupup!@#$";
    private static final String JWT_KEY_PHONE = "phone";
    //司机是1 ,乘客是2
    private static final String JWT_KEY_IDENTITY = "identity";
    private static final String JWT_TOKEN_TYPE = "tokenType";
    private static final String JWT_TOKEN_TIME = "tokenTime";


    public static String generatorToken(String phone,String identity,String tokenType){

        Map<String, String> map = new HashMap<>();

        map.put(JWT_KEY_PHONE,phone);
        map.put(JWT_KEY_IDENTITY,identity);
        map.put(JWT_TOKEN_TYPE,tokenType);
        //防止每次生成的token一样,加一个时间参数
        map.put(JWT_TOKEN_TIME, Calendar.getInstance().getTime().toString());

        JWTCreator.Builder builder = JWT.create();

        //整合map
        map.forEach(
                (k,v) ->{
                    builder.withClaim(k,v);
                }
        );

        //整合过期时间,由redis控制,弃用
        /*
        *Date time = Calendar.getInstance().getTime();
        *builder.withExpiresAt(time);
        * */

        //生成token
        String sign = builder.sign(Algorithm.HMAC256(SIGN));

        return sign;
    }


    /*
    * 检验token
    * 主要看看token是否异常
    * */
    public static TokenResult checkToken(String token) {

        TokenResult tokenResult = null;

        try {
            tokenResult = JwtUtils.parseToken(token);
        } catch (Exception e) {

        }

        return tokenResult;

    }

    /*
    * 解析token
    * */
    private static TokenResult parseToken(String token) {

        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        String phone = verify.getClaim(JWT_KEY_PHONE).asString();
        String identify = verify.getClaim(JWT_KEY_IDENTITY).asString();

        TokenResult tokenResult = new TokenResult();

        tokenResult.setPhone(phone);
        tokenResult.setIdentity(identify);

        return tokenResult;


    }
}
